#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->comboSerial->installEventFilter(this);

    QSettings config("config.ini", QSettings::IniFormat);

    foreach (QSerialPortInfo portInfo, QSerialPortInfo::availablePorts())
    {
        ui->comboSerial->addItem(portInfo.portName() + " " + portInfo.description());
    }

    ui->comboBaudrate->addItem("2400");
    ui->comboBaudrate->addItem("4800");
    ui->comboBaudrate->addItem("9600");
    ui->comboBaudrate->addItem("14400");
    ui->comboBaudrate->addItem("19200");
    ui->comboBaudrate->addItem("38400");
    ui->comboBaudrate->addItem("56000");
    ui->comboBaudrate->addItem("57600");
    ui->comboBaudrate->addItem("115200");
    ui->comboBaudrate->addItem("128000");
    ui->comboBaudrate->addItem("230400");
    ui->comboBaudrate->addItem("256000");
    ui->comboBaudrate->addItem("460800");
    ui->comboBaudrate->addItem("500000");
    ui->comboBaudrate->addItem("512000");
    ui->comboBaudrate->addItem("600000");
    ui->comboBaudrate->setCurrentIndex(ui->comboBaudrate->findText(config.value("baudrate", 115200).toString()));

    ui->comboChipType->addItem("STM32F0");
    ui->comboChipType->addItem("STM32F1");
    ui->comboChipType->addItem("STM32F2");
    ui->comboChipType->addItem("STM32F3");
    ui->comboChipType->addItem("STM32F4");
    ui->comboChipType->addItem("STM32F7");
    ui->comboChipType->addItem("STM32L0");
    ui->comboChipType->addItem("STM32L1");
    ui->comboChipType->addItem("STM32L4");
    ui->comboChipType->addItem("STM32H7");
    ui->comboChipType->setCurrentIndex(ui->comboChipType->findText(config.value("chipType").toString()));

    ui->comboSerial->setCurrentIndex(ui->comboSerial->findText(config.value("portname").toString()));
    ui->lineEdit->setText(config.value("filepath").toString());

    ui->ckboxReadProtect->setChecked(config.value("readProtect", false).toBool());

    QObject::connect(ui->btnSelectFile, SIGNAL(clicked(bool)), this, SLOT(selectFile()));
    QObject::connect(ui->btnDownload, SIGNAL(clicked(bool)), this, SLOT(download()));

    thread = new QThread();
    downloader = new QDownloadHandler();
    QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    QObject::connect(thread, SIGNAL(finished()), downloader, SLOT(deleteLater()));
    QObject::connect(downloader, SIGNAL(error(QString)), this, SLOT(downlaodError(QString)));
    QObject::connect(downloader, SIGNAL(information(QString)), this, SLOT(downlaodInfo(QString)));
    QObject::connect(downloader, SIGNAL(progress(int)), ui->progressBar, SLOT(setValue(int)));
    QObject::connect(this, SIGNAL(isp()), downloader, SLOT(download()));
    downloader->moveToThread(thread);
    thread->start();
}

MainWindow::~MainWindow()
{
    QSettings config("config.ini", QSettings::IniFormat);
    config.setValue("portname", ui->comboSerial->currentText());
    config.setValue("filepath", ui->lineEdit->text());
    config.setValue("chipType", ui->comboChipType->currentText());
    config.setValue("baudrate", ui->comboBaudrate->currentText());
    config.setValue("readProtect", ui->ckboxReadProtect->isChecked());
    delete ui;
}

void MainWindow::selectFile()
{
    QString currText = ui->lineEdit->text();
    QString fileName = QFileDialog::getOpenFileName(this, tr("选择固件"), currText, tr("二进制文件 (*.bin *.BIN)"));
    if(fileName.isEmpty())
    {
        fileName = currText;
    }
    ui->lineEdit->setText(fileName);
}

void MainWindow::download()
{
    if(!downloader->isDownloading())
    {
        ui->textBrowser->clear();
        ui->progressBar->setValue(0);
        if(ui->comboSerial->currentText().isEmpty())
        {
            downlaodError("未发现串口！");
            return;
        }
        if(ui->lineEdit->text().isEmpty())
        {
            downlaodError("未选择固件！");
            return;
        }
        downloader->setBaudrate(ui->comboBaudrate->currentText().toInt());
        downloader->setChipName(ui->comboChipType->currentText());
        downloader->setPortName(ui->comboSerial->currentText().split(" ")[0]);
        downloader->setFileName(ui->lineEdit->text());
        downloader->setReadProtcet(ui->ckboxReadProtect->isChecked());
        emit isp();
    }
}

void MainWindow::downlaodError(QString msg)
{
    QMessageBox::critical(this, "错误提示", msg, "关闭");
}

void MainWindow::downlaodInfo(QString msg)
{
    ui->textBrowser->append(msg);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        if(watched == ui->comboSerial)
        {
            QComboBox* comboBox = qobject_cast<QComboBox *>(watched);
            comboBox->clear();
            QList<QSerialPortInfo> serials = QSerialPortInfo::availablePorts();
            foreach (QSerialPortInfo info, serials)
            {
                comboBox->addItem(info.portName() + " " + info.description());
            }
        }
    }
    return QMainWindow::eventFilter(watched, event);
}
